package com.happyhome.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import com.happyhome.constants.ComUnitName;
import com.happyhome.constants.RecordStatus;
import com.happyhome.datamodel.QRoomUtility;
import com.happyhome.datamodel.QUtility;
import com.happyhome.datamodel.Utility;
import com.mysema.query.BooleanBuilder;
import com.mysema.query.jpa.JPQLQuery;
import com.mysema.query.jpa.impl.JPAQuery;
import com.trg.dao.jpa.GenericDAOImpl;

@Repository
public class UtilityDaoImpl extends GenericDAOImpl<Utility, Long> implements UtilityDao{
	
	@SuppressWarnings("unused")
	private static final Logger LOGGER = LoggerFactory.getLogger(UtilityDaoImpl.class);
	
	@Override
	@PersistenceContext(unitName = ComUnitName.COM_UNIT)
	public void setEntityManager(EntityManager entityManager) {
		super.setEntityManager(entityManager);
	}

	@Override
	public List<Utility> getAllUtilities() {
		JPQLQuery query = new JPAQuery(em());
		QUtility utilities = QUtility.utility;
		
		query.from(utilities);
		
		BooleanBuilder where = new BooleanBuilder();
		
		where.and(utilities.status.eq(RecordStatus.TRUE));
		
		query.where(where);
		
		List<Utility> listUtilities = query.list(utilities);
		return listUtilities;
	}

	@Override
	public Utility getUtilityByCode(String code) {
		JPQLQuery query = new JPAQuery(em());
		QUtility utilities = QUtility.utility;
		
		query.from(utilities);
		
		BooleanBuilder where = new BooleanBuilder();
		
		where.and(utilities.status.eq(RecordStatus.TRUE))
			 .and(utilities.codeUtility.eq(code));
		
		query.where(where);
		
		Utility utility = query.uniqueResult(utilities);
		return utility;
	}

	@Override
	public List<Utility> getAllUtilitiesByAId(Long aId) {
		JPQLQuery query = new JPAQuery(em());
		QUtility utilities = QUtility.utility;
		QRoomUtility roomUtility = QRoomUtility.roomUtility;
		
		BooleanBuilder where = new BooleanBuilder();
		
		where.and(utilities.status.eq(RecordStatus.TRUE))
			 .and(roomUtility.room.idRoom.eq(aId));
		
		query.from(roomUtility).leftJoin(roomUtility.utility, utilities).where(where);
		
		List<Utility> listUtilities = query.list(utilities);
		return listUtilities;
	}

}
